package com.monkeyboy.utils;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class EncryptUtils {

	private static Logger logger = LoggerFactory.getLogger(EncryptUtils.class);

	public static PrivateKey getPrivateKeyPKCS8(String base64key) {
		try {
			KeyFactory keyFactory = KeyFactory.getInstance("RSA");
			PKCS8EncodedKeySpec encodedPubKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(base64key));
			return keyFactory.generatePrivate(encodedPubKeySpec);
		} catch (Exception ex) {
			throw new RuntimeException(ex.getMessage(), ex);
		}
	}

	public static byte[] signatureMD5WithRSA(byte[] orgData, PrivateKey privKey) {
		try {
			Signature sign = Signature.getInstance("MD5withRSA");
			sign.initSign(privKey);
			sign.update(orgData);
			byte[] signed = sign.sign();
			return signed;
		} catch (Exception ex) {
			throw new RuntimeException(ex.getMessage(), ex);
		}
	}

	public static PublicKey getPubKeyPKCS8(String base64key) {
		try {
			KeyFactory keyFactory = KeyFactory.getInstance("RSA");
			X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.decodeBase64(base64key));
			return keyFactory.generatePublic(x509KeySpec);
		} catch (Exception ex) {
			throw new RuntimeException(ex.getMessage(), ex);
		}
	}

	public static String encryptPrivate(String data, String prKey) {
		String signMsg = StringUtils.EMPTY;
		PrivateKey privateKey = getPrivateKeyPKCS8(prKey);
		try {
			signMsg = Hex.encodeHexString(signatureMD5WithRSA(data.getBytes("utf-8"), privateKey));
		} catch (UnsupportedEncodingException e) {
			logger.error("",e);
		}
		return signMsg;
	}

	public static boolean checkSign(String data, String sign, String pubKey) {
		boolean ret = true;
		PublicKey publicKey = getPubKeyPKCS8(pubKey);
		Signature signature;
		try {
			signature = Signature.getInstance("MD5withRSA");
			signature.initVerify(publicKey);
			signature.update(data.getBytes("utf-8"));
			ret = signature.verify(Hex.decodeHex(sign.toCharArray()));
		} catch (Exception e) {
			logger.error("",e);
		}
		return ret;
	}
}
